<template>
<el-card class="box-card">
  <div slot="header" class="clearfix">
    <span>重置密码</span>
  </div>
<el-form label-width="100px" :model="userPassword" :rules="userPasswordRules" ref="userInfoPwd">
    <el-form-item label="原密码" prop="old_pwd">
      <el-input v-model="userPassword.old_pwd"></el-input>
    </el-form-item>
    <el-form-item label="新密码" prop="new_pwd">
      <el-input type="password"  v-model="userPassword.new_pwd"></el-input>
    </el-form-item>
    <el-form-item label="确认新密码" prop="re_pwd">
      <el-input  type="password" v-model="userPassword.re_pwd"></el-input>
    </el-form-item>
     <el-form-item>
      <el-button type="primary" @click="updatePassword">修改密码</el-button>
      <el-button type="info" @click="resetFn">重置</el-button>
    </el-form-item>
  </el-form>
</el-card>
</template>

<script>
import { updateUserPasswordAPI } from '@/api'
import { mapMutations } from 'vuex'
export default {
  name: 'userPassword',
  data () {
    const samePwd = (rule, value, callback) => {
      if (value === this.userPassword.old_pwd) {
        return callback(new Error('新旧密码不能相同'))
      }
      callback()
    }

    const rePwd = (rule, value, callback) => {
      if (value !== this.userPassword.new_pwd) {
        return callback(new Error('两次密码不一致'))
      }
      callback()
    }
    return {
      userPassword: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      userPasswordRules: {
        old_pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { pattern: /^\S{6,15}$/, message: '密码长度必须是6-15位的非空字符串', trigger: 'blur' },
          { validator: samePwd, trigger: 'blur' }
        ],
        re_pwd: [
          { required: true, message: '请再次确认新密码', trigger: 'blur' },
          { validator: rePwd, trigger: 'blur' }
        ]
      }

    }
  },
  methods: {
    ...mapMutations(['updateToken', 'updateUserInfo']),
    updatePassword () {
      this.$refs.userInfoPwd.validate(async valid => {
        if (!valid) return false
        const { data: res } = await updateUserPasswordAPI(this.userPassword)
        console.log(res)
        if (res.code !== 0) return this.$message.error('原密码错误！')
        this.updateToken('')// 清除token
        this.updateUserInfo({})// 清除用户信息
        this.$router.push('/login')// 返回登录页
        this.$refs.userInfoPwd.resetFields()
        this.$message.success('修改密码成功，请重新登录！')
      })
    },
    resetFn () {
      this.$refs.userInfoPwd.resetFields()
    }
  }
}
</script>

<style lang='less' scoped>
.el-form {
    width: 500px;
}
</style>
